package com.bsuir.avareader;

import java.io.File;
import java.util.HashMap;
import java.util.Map;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.ActivityInfo;
import android.graphics.Color;
import android.graphics.Typeface;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.preference.PreferenceManager;
import android.text.InputType;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
import android.view.WindowManager;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.ViewFlipper;

import com.bsuir.avareader.logic.BookManager;
import com.bsuir.avareader.textprocessing.ITextHandler;
import com.bsuir.avareader.textprocessing.TextHandlerCreator;

public class MainActivity extends Activity implements OnTouchListener {
	private final static int ID_DLG_PROGRESS = 11;
	private static final int ID_DLG_GO_TO = 12;
	private static final int ID_DLG_GO_ON = 13;

	private ProgressDialog progress;
	private BookManager bookManager;

	private TextView txtvw;
	private TextView currenttext;
	private TextView previoustext;
	private TextView nexttext;
	private int nprev = 0, ncurr = 1, nnext = 2;
	private Menu menu;
	boolean bNightMode;
	int n = -1;
	int nmax;
	int length = 800;
	String str;
	private boolean mNightMode;
	SharedPreferences getPrefs;
	private ViewFlipper flipper;
	private float fromPosition;
	File[] mFile = new File[1];
	private Map<String, Integer> backGrounds = new HashMap<String, Integer>();

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);

		// // int mesHeight = txtvw.getMeasuredHeight();
		// // int mesWidth = txtvw.getMeasuredWidth();
		// // length = mesHeight*mesWidth;
		getPrefs = PreferenceManager.getDefaultSharedPreferences(this
				.getBaseContext());

	
		LinearLayout mainLayout = (LinearLayout) findViewById(R.id.main_layout);
		mainLayout.setOnTouchListener(this);
	  
		flipper = (ViewFlipper) findViewById(R.id.flipper);

		LayoutInflater inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
		int layouts[] = new int[] { R.layout.previouspage,
				R.layout.currentpage, R.layout.nextpage };
		for (int layout : layouts)
			flipper.addView(inflater.inflate(layout, null));

		// int mesHeight = txtvw.getMeasuredHeight();
		// int mesWidth = txtvw.getMeasuredWidth();
		// length = mesHeight*mesWidth;

		nmax = getString(R.string.text).length() / length;
		str = getString(R.string.text);
		previoustext = (TextView) flipper.getCurrentView().findViewById(
				R.id.previoustext);
		flipper.showNext();
		currenttext = (TextView) flipper.getCurrentView().findViewById(
				R.id.currenttext);
		flipper.showNext();
		nexttext = (TextView) flipper.getCurrentView().findViewById(
				R.id.nexttext);
		flipper.showPrevious();
		flipper.showPrevious();
		previoustext.setText(SetTextBuffer(nprev));
		currenttext.setText(SetTextBuffer(ncurr));
		nexttext.setText(SetTextBuffer(nnext));

		bookManager = new BookManager(this);

		backGrounds.put("beige", R.drawable.back_beige);
		backGrounds.put("green", R.drawable.back_green);
		backGrounds.put("light", R.drawable.back_light);
		backGrounds.put("peper", R.drawable.back_peper);
		backGrounds.put("white", R.drawable.back_white);
	}

	@Override
	public void onResume() {
		super.onResume();
		getPrefs = PreferenceManager.getDefaultSharedPreferences(this
				.getBaseContext());
		String fonttypeface = getPrefs.getString("fonttypeface", "Sans");
		String fontcolor = getPrefs.getString("fontcolor", "black");
		int fontSize = Integer.parseInt(getPrefs.getString("fontsize", "20"));
		int brightness = Integer.parseInt(getPrefs
				.getString("brightness", "80"));
		mNightMode = getPrefs.getBoolean("nightMode", false);
		String back = getPrefs.getString("background", "white");
		int background = backGrounds.get(back);
		boolean bFullScreen = getPrefs.getBoolean("fullscreen", false);
		boolean bAnimation = getPrefs.getBoolean("animation", false);
		int paddingLeft = Integer.parseInt(getPrefs.getString("padding_left",
				"6"));
		int paddingRight = Integer.parseInt(getPrefs.getString("padding_right",
				"6"));
		int paddingTop = Integer.parseInt(getPrefs
				.getString("padding_top", "6"));
		int paddingBottom = Integer.parseInt(getPrefs.getString(
				"padding_bottom", "6"));
		String orientation = getPrefs.getString("orientation", "portrait");

		// set orientation
		if (orientation.equals("landscape")) {
			setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
		} else {
			setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
		}

		// set fullscreen
		if (bFullScreen) {
			getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
					WindowManager.LayoutParams.FLAG_FULLSCREEN);
		} else {
			getWindow().clearFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);
		}

		// set brightness
		WindowManager.LayoutParams lp = getWindow().getAttributes();
		lp.screenBrightness = brightness / 100.0f;
		getWindow().setAttributes(lp);

		// set font size
		previoustext.setTextSize(fontSize);
		currenttext.setTextSize(fontSize);
		nexttext.setTextSize(fontSize);
		// set font type
		previoustext
				.setTypeface(Typeface.create(fonttypeface, Typeface.NORMAL));
		currenttext.setTypeface(Typeface.create(fonttypeface, Typeface.NORMAL));
		nexttext.setTypeface(Typeface.create(fonttypeface, Typeface.NORMAL));
		// set gravity
		previoustext.setGravity(Gravity.LEFT);
		currenttext.setGravity(Gravity.LEFT);
		nexttext.setGravity(Gravity.LEFT);
		// set font color

		previoustext.setTextColor(Color.parseColor(fontcolor));
		currenttext.setTextColor(Color.parseColor(fontcolor));
		nexttext.setTextColor(Color.parseColor(fontcolor));
		// set padding
		previoustext.setPadding(paddingLeft, paddingTop, paddingRight,
				paddingBottom);
		currenttext.setPadding(paddingLeft, paddingTop, paddingRight,
				paddingBottom);
		nexttext.setPadding(paddingLeft, paddingTop, paddingRight,
				paddingBottom);
		// set background
		mNightMode = getPrefs.getBoolean("nightMode", false);

		if (mNightMode) {
			previoustext.setBackgroundResource(R.drawable.back_dark_blue);
			currenttext.setBackgroundResource(R.drawable.back_dark_blue);
			nexttext.setBackgroundResource(R.drawable.back_dark_blue);
			previoustext.setTextColor(Color.parseColor("white"));
			currenttext.setTextColor(Color.parseColor("white"));
			nexttext.setTextColor(Color.parseColor("white"));
		} else {
			previoustext.setBackgroundResource(background);
			currenttext.setBackgroundResource(background);
			nexttext.setBackgroundResource(background);
			previoustext.setTextColor(Color.parseColor(fontcolor));
			currenttext.setTextColor(Color.parseColor(fontcolor));
			nexttext.setTextColor(Color.parseColor(fontcolor));
		}

	}

	private String SetTextBuffer(int n) {

		String str = getString(R.string.text);
		char[] buffer = str.toCharArray();
		String newstr = str.valueOf(buffer, n * length, length);
		return newstr;
	}


	public boolean onTouch(View view, MotionEvent event) {
		int nm = -1;
		switch (event.getAction()) {
		case MotionEvent.ACTION_DOWN:
			fromPosition = event.getX();
			break;
		case MotionEvent.ACTION_MOVE:
			float toPosition = event.getX();
		 
			int MOVE_LENGTH = 100;
			if ((fromPosition - MOVE_LENGTH) > toPosition) {
				fromPosition = toPosition;
				flipper.setInAnimation(AnimationHelper.inFromRightAnimation());
				flipper.setOutAnimation(AnimationHelper.outToLeftAnimation());
				// flipper.setInAnimation(AnimationUtils.loadAnimation(this,R.anim.go_next_in));
				// flipper.setOutAnimation(AnimationUtils.loadAnimation(this,R.anim.go_next_out));
				if (nm <= nmax) {
					if (n < nmax)
						flipper.showNext();
					n++;
					nm = Math.min(Math.min(nprev, ncurr), nnext);
					if (nm == nprev)
						nprev += 3;
					else if (nm == ncurr)
						ncurr += 3;
					else if (nm == nnext)
						nnext += 3;
					previoustext.setText(SetTextBuffer(nprev));
					currenttext.setText(SetTextBuffer(ncurr));
					nexttext.setText(SetTextBuffer(nnext));
				}
			} else if ((fromPosition + MOVE_LENGTH) < toPosition) {
				fromPosition = toPosition;
				flipper.setInAnimation(AnimationHelper.inFromLeftAnimation());
				flipper.setOutAnimation(AnimationHelper.outToRightAnimation());
				// flipper.setInAnimation(AnimationUtils.loadAnimation(this,R.anim.go_prev_in));
				// flipper.setOutAnimation(AnimationUtils.loadAnimation(this,R.anim.go_prev_out));
				if (nm >= 0) {
					flipper.showPrevious();
					n--;
					nm = Math.max(Math.max(nprev, ncurr), nnext);
					if (nm == nprev)
						nprev -= 3;
					else if (nm == ncurr)
						ncurr -= 3;
					else if (nm == nnext)
						nnext -= 3;
					// if((n>=1) && (n<=nmax-1))
					// {
					previoustext.setText(SetTextBuffer(nprev));
					currenttext.setText(SetTextBuffer(ncurr));
					nexttext.setText(SetTextBuffer(nnext));
				}
			}

		default:
			break;
		}
		return true;
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		this.menu = menu;
		MenuInflater inflater = getMenuInflater();
		inflater.inflate(R.menu.main_menu, menu);
		mNightMode = getPrefs.getBoolean("nightMode", false);
		if (mNightMode) {
			menu.findItem(R.id.mode).setTitle(R.string.night_mode);
			menu.findItem(R.id.mode).setIcon(R.drawable.ic_menu_night);
		} else {
			menu.findItem(R.id.mode).setTitle(R.string.day_mode);
			menu.findItem(R.id.mode).setIcon(R.drawable.ic_menu_day);
		}
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case R.id.open_file:
			// activity for result OpenFileActivity
			Intent intent = new Intent(this, OpenFileActivity.class);
			startActivityForResult(intent, 1);

			return true;
		case R.id.go_to:
			// go_to();
			return true;
		case R.id.go_on:
			// go_on();
			return true;
		case R.id.bookmarks:
			// send intent with nameBook, numScreen, allScreens
			startActivity(new Intent(this, BookmarksActivity.class));
			return true;
		case R.id.settings:
			startActivity(new Intent(this, SettingsActivity.class));
			return true;
		case R.id.info_book:
			//
			return true;
		case R.id.mode:
			changeMode();
			return true;
		default:
			return super.onOptionsItemSelected(item);
		}
	}

	private void changeMode() {
		mNightMode = getPrefs.getBoolean("nightMode", false);
		if (mNightMode) {
			menu.findItem(R.id.mode).setTitle(R.string.day_mode);
			menu.findItem(R.id.mode).setIcon(R.drawable.ic_menu_day);
			mNightMode = false;
		} else {
			menu.findItem(R.id.mode).setTitle(R.string.night_mode);
			menu.findItem(R.id.mode).setIcon(R.drawable.ic_menu_night);
			mNightMode = true;
		}
		SharedPreferences.Editor editor = getPrefs.edit();
		editor.putBoolean("nightMode", mNightMode);

		editor.commit();
		setMode();
	}

	private void setMode() {

		this.onResume();
	}

	private void go_on() {
		// TODO Auto-generated method stub
		showDialog(ID_DLG_GO_ON);
	}

	private void go_to() {
		// TODO Auto-generated method stub
		showDialog(ID_DLG_GO_TO);
	}

	@Override
	protected Dialog onCreateDialog(int id) {
		Dialog dialog = null;
		switch (id) {
		case ID_DLG_PROGRESS:
			progress = new ProgressDialog(this);
			progress.setMessage("Loading ...");
			dialog = progress;
			break;
		case ID_DLG_GO_TO:
			AlertDialog.Builder builderGoTo = new AlertDialog.Builder(this);
			builderGoTo.setMessage(R.string.dlg_go_to);
			final EditText inputTo = new EditText(this);
			builderGoTo.setView(inputTo);
			inputTo.setInputType(InputType.TYPE_CLASS_NUMBER);
			builderGoTo.setPositiveButton(R.string.go,
					new DialogInterface.OnClickListener() {
						@Override
						public void onClick(DialogInterface dialog, int which) {
							String value = inputTo.getText().toString().trim();
							//
						}
					});
			builderGoTo.setNegativeButton(R.string.cancel,
					new DialogInterface.OnClickListener() {
						@Override
						public void onClick(DialogInterface dialog, int which) {
							dialog.cancel();
						}
					});
			builderGoTo.setCancelable(false);
			dialog = builderGoTo.create();
			break;
		case ID_DLG_GO_ON:
			AlertDialog.Builder builderGoOn = new AlertDialog.Builder(this);
			builderGoOn.setMessage(R.string.dlg_go_on);
			final EditText inputOn = new EditText(this);
			builderGoOn.setView(inputOn);
			inputOn.setInputType(InputType.TYPE_CLASS_NUMBER);
			builderGoOn.setPositiveButton(R.string.go,
					new DialogInterface.OnClickListener() {
						@Override
						public void onClick(DialogInterface dialog, int which) {
							String value = inputOn.getText().toString().trim();
							//
						}
					});
			builderGoOn.setNegativeButton(R.string.cancel,
					new DialogInterface.OnClickListener() {
						@Override
						public void onClick(DialogInterface dialog, int which) {
							dialog.cancel();
						}
					});
			builderGoOn.setCancelable(false);
			dialog = builderGoOn.create();
			break;
		default:
			dialog = null;
		}
		return dialog;
	}

	void updateProgress(long percent) {
		progress.setMessage("Loaded " + percent + "%");
	}

	class ParseTextbookTask extends AsyncTask<File, Void, Void> {
		private MainActivity mainActivity;
		private ITextHandler texthandler;

		public ParseTextbookTask(MainActivity activity) {
			mainActivity = activity;
		}

		@Override
		protected Void doInBackground(File... params) {
			File file = (params.length > 0) ? params[0] : null;

			if (file != null) {
				texthandler = TextHandlerCreator.Create(
						getApplicationContext(), file);
				texthandler.parseTextbook(currenttext, 0, 0);
			}
			return null;
		}

		@Override
		protected void onProgressUpdate(Void... values) {
			super.onProgressUpdate(values);
			mainActivity.updateProgress(0);
			showDialog(ID_DLG_PROGRESS);
		}

		@Override
		protected void onPostExecute(Void result) {
			super.onPostExecute(result);
			dismissDialog(ID_DLG_PROGRESS);
		}

	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		if (data == null) {
			return;
		}
		String filePath = data.getStringExtra("file");

		File file = new File(filePath);
		mFile[0] = file;
		new ParseTextbookTask(this).execute(mFile);
	}

}